/**
 * Copyright (c) 2015-2017, Henry Yang 杨勇 (gismail@foxmail.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lambkit.module.upms;

import com.google.common.collect.Lists;
import com.jfinal.kit.StrKit;
import com.lambkit.Lambkit;
import com.lambkit.common.util.EncryptUtils;
import com.lambkit.common.util.StringUtils;
import com.lambkit.core.config.ConfigManager;
import com.lambkit.module.upms.api.UpmsApiService;
import com.lambkit.module.upms.record.UpmsUser;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

public class UpmsManager {

	private static final UpmsManager me = new UpmsManager();

	public static UpmsManager me() {
		return me;
	}
	
	private UpmsApiService upmsApiService;
	private UpmsConfig config;
	private UpmsCache cache;
	private boolean useable = false;
	
	private List<String> extUrls;
	
	public UpmsManager() {
		setExtUrls(Lists.newArrayList());
	}
	
	public UpmsConfig getConfig() {
		if(config==null) {
			config = Lambkit.config(UpmsConfig.class);
		}
		return config;
	}
	
//	public UpmsApiService getUpmsApiService() {
//		UpmsConfig upmsConfig = getConfig();
//		if (upmsApiService == null) {
//			if ("client".equals(upmsConfig.getType())) {
//				upmsApiService = RpcKit.obtain(UpmsApiService.class);
//			} else {
//				upmsApiService = Lambkit.get(UpmsApiService.class);
//			}
//		}
//		return upmsApiService;
//    }
	public UpmsApiService getUpmsApiService() {
        if(upmsApiService==null) {
            UpmsConfig upmsConfig = ConfigManager.me().get(UpmsConfig.class);
            if("client".equals(upmsConfig.getType())) {
            	UpmsService upmsService = new UpmsService();
            	upmsApiService = upmsService.service(UpmsApiService.class);
                //upmsApiService = RpcKit.obtain(UpmsApiService.class);
                //upmsUserAccountService = RpcKit.obtain(UpmsUserAccountService.class);
                //upmsUserAccountRoleService = RpcKit.obtain(UpmsUserAccountRoleService.class);
            } else {
                upmsApiService = Lambkit.get(UpmsApiService.class);
            }
        }
        return upmsApiService;
    }

	public UpmsCache getCache() {
		if(cache==null) {
			cache = new UpmsCache();
		}
		return cache;
	}

	public void setCache(UpmsCache cache) {
		this.cache = cache;
	}
	
	public UpmsUser currentUser() {
		// 登录信息
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        if(StrKit.notBlank(username)) {
        	UpmsUser upmsUser = UpmsManager.me().getUpmsApiService().selectUpmsUserByUsername(username);
            return upmsUser;
        }
        return null;
	}
	
	public UpmsUser getUser(String sessionId) {
		// 判断是否已登录，如果已登录，则回跳
        String code = getCache().getSession(sessionId);
        // code校验值
        if (StringUtils.isNotBlank(code) && code.startsWith(sessionId + "&")) {
        	//String username = code.substring(code.lastIndexOf("&"));
            String username = code.replace(sessionId + "&", "");
            if(StrKit.notBlank(username)) {
            	UpmsUser upmsUser = UpmsManager.me().getUpmsApiService().selectUpmsUserByUsername(username);
                return upmsUser;
            }
        }
        return null;
	}
	
	/**
	 * 验证url是否需要upms拦截
	 * @param target
	 * @return
	 */
	public boolean validateUrl(String target) {
		for (String url : extUrls) {
			if(target.startsWith(url)) {
				return false;
			}
		}
		return true;
	}
	
	public void addExtUrl(String url) {
		extUrls.add(url);
	}

	public List<String> getExtUrls() {
		return extUrls;
	}

	public void setExtUrls(List<String> extUrls) {
		this.extUrls = extUrls;
	}

	public boolean isUseable() {
		return useable;
	}

	public void setUseable(boolean useable) {
		this.useable = useable;
	}

	public boolean hasAnyRoles(UpmsUser user, String roleNames) {
		return getUpmsApiService().hasAnyRoles(user.getUserId(), roleNames);
	}

	public boolean hasRule(UpmsUser user, Long ruleid) {
		return getUpmsApiService().hasRule(user.getUserId(), ruleid);
	}

	public String encrypt(String passwordAndsalt) {
		return encrypt(passwordAndsalt, getConfig().getPasswordEncrypt());
	}

	public String encrypt(String passwordAndsalt, String type) {
		if("sha".equals(type)) {
			return EncryptUtils.sha(passwordAndsalt);
		} else if("md5".equals(type)) {
			return EncryptUtils.md5(passwordAndsalt);
		}
		return EncryptUtils.MD5(passwordAndsalt);
	}

	public boolean rexCheckPassword(String input) {
		// 6-32 位，字母、数字、字符
		String regStr = "^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_]+$)(?![a-z0-9]+$)(?![a-z\\W_]+$)(?![0-9\\W_]+$)[a-zA-Z0-9\\W_]{6,32}$";
		return input.matches(regStr);
	}
}
